import { Injectable } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { InjectModel } from '@nestjs/mongoose'
import * as bcrypt from 'bcryptjs'
import * as jwt from 'jsonwebtoken'
import { Model } from 'mongoose'
import { LoginDto, RegisterDto, UpdateProfileDto } from '../../../dto/auth.dto'
import { User } from '../../models/User'
import { RedisService } from '../redis/RedisService'

@Injectable()
export class AuthService {
  constructor(
    private readonly configService: ConfigService,
    private readonly redisService: RedisService,
    @InjectModel(User.name) private userModel: Model<User>
  ) {}

  async validateToken(token: string): Promise<boolean> {
    // 实现token验证逻辑
    return true
  }

  async generateToken(user: any): Promise<string> {
    const payload = { id: user._id }
    return jwt.sign(payload, this.configService.get('JWT_SECRET'), {
      expiresIn: '1h',
    })
  }

  async register(registerDto: RegisterDto) {
    const hashedPassword = await bcrypt.hash(registerDto.password, 10)
    const user = new this.userModel({
      ...registerDto,
      password: hashedPassword,
    })
    return user.save()
  }

  async login(loginDto: LoginDto) {
    const user = await this.userModel.findOne({ email: loginDto.email })
    if (!user) {
      throw new Error('用户不存在')
    }

    const isValid = await bcrypt.compare(loginDto.password, user.password)
    if (!isValid) {
      throw new Error('密码错误')
    }

    return {
      user,
      token: await this.generateToken(user),
    }
  }

  async sendResetPasswordEmail(email: string) {
    // 实现发送重置密码邮件逻辑
    return { success: true }
  }

  async resetPassword(token: string, newPassword: string) {
    // 实现重置密码逻辑
    return { success: true }
  }

  async getProfile(userId: string) {
    return this.userModel.findById(userId)
  }

  async updateProfile(userId: string, updateProfileDto: UpdateProfileDto) {
    return this.userModel.findByIdAndUpdate(userId, { $set: updateProfileDto }, { new: true })
  }
}
